﻿package com.gamemeal.media {
	import flash.display.BitmapData;
	import flash.display.BlendMode;
	import flash.display.IBitmapDrawable;
	import flash.filters.BitmapFilter;
	import flash.filters.BlurFilter;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.media.Camera;
	import flash.media.Video;
	
	import com.gamemeal.filters.CustomFilterThreshold;
	import com.gamemeal.filters.FilterPreset;
	/**
	 * @author Colin
	 */
	public final class TouchScreen {
		private var w:int=320;
		private var h:int=240;
		private var ctx:BitmapData;
		private var backgroundCTX:BitmapData;
		private var video:IBitmapDrawable;
		private var origin : Point = new Point(0,0);

		private var _filters:Array=[];

		public function TouchScreen(){
			ctx = new BitmapData(w,h,true,0);
			backgroundCTX = new BitmapData(w,h,false,0);
			video = setupVideo();

			_filters.push(FilterPreset.getRemoveNoiseFilter(4));
			_filters.push(new CustomFilterThreshold(0xFF353535));
		}
		
		private function setupVideo():IBitmapDrawable{
			var vid:Video = new Video(w,h);
			var cam:Camera = Camera.getCamera();
			cam.setMode(w,h,60);
			cam.setQuality(120000, 20);
			vid.attachCamera(cam);
			return vid;
		}

		private function process(ctx:BitmapData):void{
			for(var i:int=0;i<_filters.length;i++){
				if(_filters[i] is BitmapFilter){
					ctx.applyFilter(ctx,ctx.rect, origin, _filters[i]);
				}else{
					_filters[i].apply(ctx);
				}
			}
		}

		public function setBackground():void{
			backgroundCTX.draw(video);
			backgroundCTX.applyFilter(backgroundCTX, backgroundCTX.rect, origin, new BlurFilter());
		}

		public function getTouchRects():Array{
			ctx.draw(video);
			ctx.draw(backgroundCTX,null,null,BlendMode.SUBTRACT,null,false);
			process(ctx);

			//hit testing
			var testingX:int=0;
			var testingY:int=0;
			var count:int=0;
			var foundRects:Array=[];
			var rect:Rectangle;
			var rectCount:int=0;

			while(testingY<ctx.height){
				testingX = count%ctx.width;
				testingY = Math.floor(count/ctx.width);

				//if source pixel is FFFFFF, get the boundsRect
				if(ctx.getPixel(testingX, testingY)==0xFFFFFF){
					rectCount++;
					ctx.floodFill(testingX, testingY, 0xFF000000+rectCount);
					rect = ctx.getColorBoundsRect(0xFFFFFFFF, 0xFF000000+rectCount);
					foundRects.push(rect);
					//ctx.fillRect(rect, 0xFF00FF00);
				}

				count+=5;
				if(Math.floor(count/ctx.width)>testingY)count+=ctx.width*4;
			}
			return foundRects;
		}
		
		public function getContext():BitmapData{
			return ctx;
		}
	}
}